<template>
  <!-- 单据结构  -->
  <div>
    <div class="data-filter">
      <data-filter
        :filter-items="dataSource.tableHeader"
        @search="doSearch"
      />
    </div>
    <div class="extend-handle">
      <div class="extend-handle-left">
        <!-- <el-upload
          class="inline-block"
          accept=".xlsx, .xls"
          :on-change="fileChoice"
          :show-file-list="false"
          :auto-upload="false"
        >
          <el-button
            class="handle-btn"
            color="#4a78bd"
            style="color: #666"
            plain
          >
            导入Excel更新
          </el-button>
        </el-upload> -->

        <div class="ml10">
          当前账单：
          <el-input
            v-model="name"
            clearable
            style="width:220px"
            :placeholder="`请选择方案`"
            :disabled="true"
          >
            <template #append>
              <el-button @click="selectScheme">
                <el-icon><Edit /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
      </div>
    </div>
    <v-table
      ref="table"
      need-end-handle
      need-check-box
      need-customize-cell-renderer
      row-key="roleId"
      :end-handle-width="220"
      :total="dataSource.total"
      :current-page="dataSource.currentPage"
      :page-size="dataSource.pageSize"
      :table-data="dataSource.tableData"
      :columns="dataSource.tableHeader"
      :loading="loading&&!selectTableData.isShow&&!showUpdateDialog"
      :default-end-handle="false"
      :customize-end-handle="customizeEndHandle"
      :for-mat-data="dataSource.forMatData"
      :customize-cell-renderer="customizeCellRenderer"
      @selectionChange="dataSource.selectionChange($event, dataSource, proxy.$refs.table)"
      @refresh="dataSource.initData(dataSource, proxy.$refs.table)"
      @current-change="dataSource.currentPageChange($event, dataSource, proxy.$refs.table)"
      @sizeChange="dataSource.pageSizeChange($event, dataSource, proxy.$refs.table)"
      @editTableHeader="isShowEditTableHeader = true"
    />
    <selectDialogTable
      v-if="selectTableData.isShow"
      ref="dialogSearch"
      :use-choose="false"
      :append-table-style="{ background: '#126f9e', color: '#fff', borderColor: 'rgba(192, 192, 192,.5)' }"
      :width="'60%'"
      :search-input-placeholder="selectTableData.searchPlaceholde"
      :is-show="selectTableData.isShow"
      :data-source="selectTableData.dataSource"
      :title="'选择数据'"
      is-show-search-input
      :loading="loading"
      @close-dialog="selectTableData.isShow=false"
      @do-dialog-search="selectTableData.doSearch"
      @choose-row="selectTableData.chooseRow"
    />
    <el-dialog
      v-model="showUpdateDialog"
      lock-scroll
      title="账单字段更新日志"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      top="4%"
      destroy-on-close
    >
      <template #header="{ titleId, titleClass }">
        <div class="jx-dialog-header">
          <div :id="titleId" :class="titleClass">
            <h4 class="inline-block">
              账单字段更新日志
            </h4>
          </div>
          <div>
            <el-button
              class="dialog-close-btn" type="danger"
              icon="CloseBold"
              circle
              @click="showUpdateDialog = false"
            />
          </div>
        </div>
      </template>

      <div>
        <el-select
          v-model="checkResult" placeholder="请选择要查看的字段"
          style="width: 240px"
          @change="selectChange"
        >
          <el-option
            v-for="item in resultNameOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-table
          v-loading="loading" :data="updateTable"
          style="width: 100%"
        >
          <el-table-column
            prop="billCode" label="账单编码"
            width="180"
          />
          <el-table-column
            prop="resultName" label="账单字段"
            width="180"
          />
          <el-table-column
            prop="originValue" label="更新前"
            width="180"
          />
          <el-table-column
            prop="afterValue" label="更新后"
            width="180"
          />
          <el-table-column
            prop="updateTime" label="操作时间"
            width="180"
          >
            <template #default="scope">
              <div style="display: flex; align-items: center">
                {{ new proxy.$DataTool().timeStamp2Time(scope.row.updateTime,'6') }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { pbRequest } from "@/applications/sys/public/pbRequest/index"
import selectDialogTable from '@/components/public/selectDialogTable.vue'
import VTable from '@/components/public/virtualTable.vue'
import dataFilter from '@/components/public/dataFilter.vue'
import { DataSource, loading } from './utils/billingData'
import { DataSource as SummaryPlan } from './utils/summaryPlan'
import { ref, getCurrentInstance, onBeforeMount, h, watch, reactive, withDirectives, resolveDirective } from 'vue'
import { ElButton } from 'element-plus'
const authority = resolveDirective('authority')
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const checkResult = ref('')
const { proxy } = getCurrentInstance()
const isShowEditTableHeader = ref(false)
const dataSource = ref(null)
const collectSchemeCode = ref('')
const name = ref('')

watch(() => route.path, () => {
  if (route.path === '/financial/SummarizeData' && dataSource.value){
    collectSchemeCode.value = route.query.collectSchemeCode
    name.value = route.query.name
    dataSource.value.searchData.collectSchemeCode = collectSchemeCode.value
    dataSource.value.tableData.length = 0
    dataSource.value.initData(this, proxy.$refs.table)
  }
})

const initDataSource = async () => {
  collectSchemeCode.value = route.query.collectSchemeCode
  name.value = route.query.name

  dataSource.value = new DataSource({
    tableHeader: [{
      title: "所属经销商",
      dataKey: "belongArchiveName",
      key: 'belongArchiveName',
      width: 400,
      type: 'text',
      isShow: true,
      isFixed: false
    }, {
      title: "账单编码",
      dataKey: "billCode",
      key: 'billCode',
      width: 200,
      type: 'text',
      isShow: true,
      isFixed: false
    }, {
      title: "账单类型",
      dataKey: "billType",
      key: 'billType',
      width: 200,
      type: 'text',
      isShow: true,
      isFixed: false
    }, {
      title: "账期",
      dataKey: "costTerm",
      key: 'costTerm',
      width: 200,
      type: 'text',
      isShow: true,
      isFixed: false
    }],
    selectUri: '/colorful-fog/CollectResultMain/list'
  })
  if (!collectSchemeCode.value){
    selectScheme()
    return
  }
  dataSource.value.searchData = {
    collectSchemeCode: collectSchemeCode.value
  }

  dataSource.value.initData(this, proxy.$refs.table)
}

onBeforeMount(() => {
  initDataSource()
})

const doSearch = (data) => {

  if (Object.keys(data).length === 0){
    if (!collectSchemeCode.value){
      selectScheme()
      return
    }
    data.collectSchemeCode = collectSchemeCode.value
    dataSource.value.search(data, this, proxy.$refs.table)
    return
  }

  let tempData = { fieldSelectList: data }
  if (data.belongArchiveName)tempData.belongArchiveName = data.belongArchiveName
  if (data.billCode)tempData.billCode = data.billCode
  if (data.billType)tempData.billType = data.billType
  if (data.costTerm)tempData.costTerm = data.costTerm

  data = { fieldSelectList: data }
  dataSource.value.search(data, this, proxy.$refs.table)
}

const customizeEndHandle = (rowData) => {
  return [h('div', { class: 'table-handel-div' }, [withDirectives(h(
    ElButton,
    { class: 'hover-animation', onClick: () => { exportData(rowData) }, title: '导出汇总', style: 'padding:0;margin:0;background:transparent;width:80px;color:#0c81b1;margin-right:10px' },
    { default: () => "导出汇总" }), [[authority, 'SummarizeData:export']]
  )]), h('div', { class: 'table-handel-div' }, [withDirectives(h(
    ElButton,
    { class: 'hover-animation', onClick: () => { checkUpdateData(rowData) }, title: '查看修改日志', style: 'padding:0;margin:0;background:transparent;width:80px;color:#0c81b1' },
    { default: () => "修改日志" }), [[authority, 'SummarizeData:update']]
  )])]
}

const showUpdateDialog = ref(false)
const resultNameOptions = reactive([])
const checkCode = ref('')
const updateTable = reactive([])
const selectChange = (val) => {
  dataSource.value.checkUpdateData({
    billCode: checkCode.value,
    resultName: val
  }).then(res => {
    if (res.code === 200){
      updateTable.length = 0
      updateTable.push(...res.data)

    }
  })
}
const checkUpdateData = (rowData) => {

  resultNameOptions.length = 0
  checkCode.value = rowData.billCode
  dataSource.value.tableHeader.forEach(item => {
    if (item.title){
      let temp = {
        label: item.title,
        value: item.title
      }
      resultNameOptions.push(temp)
    }

  })
  showUpdateDialog.value = true

}

const customizeCellRenderer = ({ forMatValue, rowIndex, column, rowData }) => {
  return forMatValue
}

const isTimestamp = (timestamp) => {

  let regex = /^\d{13}$/
  if (regex.test(timestamp)) {
    let date = new Date(+timestamp)
    return !isNaN(date.getTime())
  }
  return false
}

const exportData = ({ billCode }) => {
  let sheetList = []
  dataSource.value.getCollectExportData({ code: billCode }).then(res => {
    if (res.code === 200){
      res.data.forEach(item => {
        let title = item.schemeName
        let header = [`所属经销商Code`, `所属经销商名称`, `账单编码`, `账期`]
        let headerCode = [`belongArchiveCode`, `belongArchiveName`, `billCode`, `costTerm`]
        let style = {}
        let sheetData = []
        item.billResultVO.resultNameList.forEach(data => {
          header.push(data.resultName)
          headerCode.push(data.resultCode)
        })

        item.billResultVO.resultDataList.list.forEach(data => {
          let temp = []
          headerCode.forEach(key => {
            if (isTimestamp(data.keyMap[key])){
              temp.push(new proxy.$DataTool().timeStamp2Time(+data.keyMap[key], 'yyyy-MM-dd hh:mm:ss'))
            } else temp.push(data.keyMap[key])
          })
          sheetData.push(temp)
        })
        sheetList.push({ title, header, style, data: sheetData })
      })
      console.log(sheetList)
      new proxy.$DataTool().complexExcel(sheetList, '账单汇总数据')
    }
  })

}

const handleXlsxData = (file) => {
  let updateList = []
  let keys = Object.keys(file[0])
  file.forEach(item => {
    keys.forEach(key => {
      console.log(item[key])
      if (item[key] && item[key].toString().indexOf(':') !== -1 && key !== '更新说明'){
        updateList.push({
          "billType": 'BILL',
          "billCode": item['账单编码'],
          "fieldName": key,
          "updateValue": item[key].split(':')[1]
        })
      }
    })
  })
  return updateList
}

const selectScheme = async () => {
  selectTableData.searchPlaceholde = '输入账单计划名称进行搜索'
  selectTableData.chooseRow = async (val) => {
    collectSchemeCode.value = val.collectSchemeCode
    name.value = val.collectSchemeName
    dataSource.value.searchData.collectSchemeCode = val.collectSchemeCode
    dataSource.value.tableData.length = 0
    dataSource.value.tableHeader.length = 0

    dataSource.value.initData(this, proxy.$refs.table)
    selectTableData.isShow = false
  }
  selectTableData.doSearch = (val) => {
    selectTableData.dataSource.searchData = { }
    if (val) selectTableData.dataSource.searchData.collectSchemeName = val
    selectTableData.dataSource.initData()
  }
  selectTableData.dataSource = new SummaryPlan({
    selectUri: `/colorful-fog/collectSchemeMain/select`,
    tableHeader: [{
      label: "汇总账单名称",
      prop: "collectSchemeName",
      width: 200
    }, {
      label: "汇总账单Code",
      prop: "collectSchemeCode",
      width: 200
    }, {
      label: "备注",
      prop: "collectSchemeDesc",
      width: 200
    }],
    pageSize: 10
  })

  selectTableData.dataSource.forMatData = (row, column) => {
    if (column.property === 'billType') return row[column.property] === 'PAY' ? '应付' : '应收'
    return row[column.property] ?? '-'
  }

  await selectTableData.dataSource.initData()
  selectTableData.isShow = true
  return
}

const selectTableData = reactive({
  isShow: false,
  dataSource: null,
  searchPlaceholde: '',
  doSearch: (val) => {
    console.log(val)
  },
  chooseRow: (val) => {
    console.log(val)
  }
})
</script>

<style lang="less" scoped>
.table{
  padding: 10px;
  background-color: #ffffff;
}
</style>
